package com.kvn.strategy;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangzhiyuan on 2018/6/11
 */
@Component
public class ShardStrategyFactory {
    @Resource
    ApplicationContext applicationContext;
    private static final List<ShardStrategy> shardStrategyList = new ArrayList<>();

    @PostConstruct
    public void init() {
        shardStrategyList.addAll(applicationContext.getBeansOfType(ShardStrategy.class).values());
    }

    public ShardStrategy findStragety(String strategy) {
        for (ShardStrategy shardStrategy : shardStrategyList) {
            if (shardStrategy.apply(strategy)) {
                return shardStrategy;
            }
        }
        throw new RuntimeException("没有找到相应的分表策略：" + strategy);
    }
}
